package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"smartLearn/conf"
	"smartLearn/models"
	"smartLearn/modules/cache"
	"smartLearn/modules/response"
	"smartLearn/public/common"
	"strconv"
	"time"
)

type LoginUser struct {
	Username string `form:"username" json:"username" binding:"required"`
	Password   string `form:"password" json:"password" binding:"required"`
}

func Logout(c *gin.Context) {
	token:=c.GetHeader("authorization")
	rc:=cache.RedisClient.Get()
	defer rc.Close()

	rc.Do("DEL",token)
	response.ShowSuccess(c,"退出成功")

}
func Login(c *gin.Context) {
	var u LoginUser
	u.Username=c.Query("username")
	u.Password=c.Query("password")


	if u.Username == "" || u.Password == "" {
		response.ShowError(c, "参数输入错误")
		return
	}

	user := models.SystemUser{Username: u.Username}
	has := user.GetRow()
	if !has {
		response.ShowError(c, "用户不存在")
		return
	}
	if common.Sha1En(u.Password+user.Salt) != user.Password {
		response.ShowError(c, "密码错误")
		return
	}

	var data = make(map[string]interface{}, 0)

	//生成token
	cur := time.Now()

	timestamps := cur.UnixNano()
	times := strconv.FormatInt(timestamps, 10)
	v:= common.Md5En(common.GetRandomString(16) + times)



	rc:=cache.RedisClient.Get()
	defer rc.Close()
	//rc.Do("set",v,user.Id,"EX",60*30)  //设置过期时间
	rc.Do("set",v,user.Id)


	log.Print(v)

	fmt.Println("设置成功")

	data[conf.Cfg.Token] = v
	response.ShowData(c, data)
	return
}
